<template>
  <div class="comprehensive-table-container auto-height-container">
    <obj-opbar
      :btn_arr="btn_arr"
      :config_table="config_table"
      :is_recycle="is_recycle"
      @add="add"
      @btn-callback="btnCallback"
      @com_del="com_del"
      @del="del"
      @fetch-data="selectData"
      @foreign-change="foreignChange"
      @get-data="getData"
      @recovery="recovery"
      @recycle="recycle"
    />

    <obj-table-base
      ref="ObjTableRef"
      :config_table="config_table"
      :detail_column="detail_column"
      :detail_hide="detail_hide"
      :detail_path="detail_path"
      :is_recycle="is_recycle"
      :light="light"
      :list="list"
      :list-loading="listLoading"
      :show_id="show_id"
      :show_selection="show_selection"
      :status-map="statusMap"
      @click-field="clickField"
      @edit="edit"
      @get-data="getData"
    />

    <vab-pagination
      :current-page="queryForm.page"
      :page-size="queryForm.page_num"
      :total="total"
      @current-change="currentChange"
      @size-change="pageChange"
    />
    <obj-edit-base ref="editRef" :rules="rules" :span="edit_span" :width="edit_width" @fetch-data="getData" />
  </div>
</template>

<script lang="ts" setup>
import { api_datalist, api_detail, api_getall, api_recycle, api_save } from '/@/api/obj_base'
const dir = '/application'
const $baseConfirm = inject<any>('$baseConfirm')
const $baseMessage = inject<any>('$baseMessage')
//设置表名
const tablename = ref<any>('sport_city')
//设置列表页是否显示id
const show_id = true
const show_selection = true
//设置列表页隐藏字段
const hide_list = reactive<any>([])
//设置编辑页
const edit_width = ref<any>('800px')
const edit_span = ref<any>('192px')
//设置必填项
const rules = reactive<any>({
  name: [{ required: true, trigger: 'blur', message: '请输入名称' }],
})

//设置详情
//const detail_path = `${dir}/obj_detail`
const detail_column = 2
const detail_hide = 'store_id,custom_id' //隐藏字段，一般是列表不显示的外键

//设置颜色字段
const statusMap: any = {
  已入账: 'success', //绿
  待入账: 'danger', //红
  已取消: 'warning', //黄
  待签署: 'info', //灰
  入账中: '', //主题色
}
//设置浅色调默真
const light = ref<boolean>(true)

//设置点击状态
const clickField = async (id: any, field: any, value: any) => {
  console.log(id, field, value)
  if (field == 'status') {
    if (value == '0' && 1 > 2) {
      //表示当前状态为0，为正常状态，点击提示是否下号
      $baseConfirm('您确定要审核吗', null, async () => {
        const { msg }: any = await api_save(tablename.value, { id: id, status: 1 })
        $baseMessage(msg, 'success', 'hey')
        await getData()
      })
    }
    if (value == '1' && 1 > 2) {
      //表示当前状态为1，为下号状态，点击提示是否上号
      $baseConfirm('您确定要取消审核吗', null, async () => {
        const { msg }: any = await api_save(tablename.value, { id: id, status: 0 })
        $baseMessage(msg, 'success', 'hey')
        await getData()
      })
    }
  }
}
//设置操作条中的按钮
// const btn_arr = [{ name: '审核', method: 'check', type: 'success' }]
//设置点击操作条中的方法
const btnCallback = async (method: any) => {
  console.log(method)
  console.log(ObjTableRef.value.selectRows) //选中的行
}
const name = tablename.value
console.log(name)
defineOptions({
  name: `${dir}Obj`,
})
const route: any = useRoute()
//通用变量
const editRef = ref<any>(null)
const ObjTableRef = ref<any>(null)
const list = ref<any>([])
const listLoading = ref<boolean>(true)
const total = ref<any>(0)

const queryForm = reactive<any>({
  page: 1,
  page_num: 10,
})
const config_table = ref<any>({})
const login_log = ref<any>({})
const is_recycle = ref<boolean>(false) //当前是否是回收站

//自定义变量

//自定义方法

//通用获取数据
const getData = async () => {
  listLoading.value = true
  api_datalist(tablename.value, queryForm).then((res: any) => {
    if (res) {
      is_recycle.value = false
      //隐藏掉隐藏的字段
      const list_show = res.config_table.list_show
      for (let i = 0; i < list_show.length; i++) {
        for (let y = 0; y < hide_list.length; y++) {
          if (list_show[i] == hide_list[y]) {
            list_show[i] = ''
          }
        }
      }
      config_table.value = res.config_table
      login_log.value = res.login_log
      list.value = res.datalist
      total.value = res.num
      listLoading.value = false
      handleMeta('DynamicMeta', { title: res.config_table.table_comment })
    }
  })
}

//设置动态标题
import { useRoutesStore } from '/@/store/modules/routes'
import { useTabsStore } from '/@/store/modules/tabs'
import getPageTitle from '/@/utils/pageTitle'
const tabsStore = useTabsStore()
const routesStore = useRoutesStore()
const { changeActiveMenu, changeMenuMeta } = routesStore
const { changeTabsMeta } = tabsStore
const handleMeta = (name: any, meta: { title: string }) => {
  if (meta.title) useTitle().value = getPageTitle(meta.title)
  changeMenuMeta({ name, meta })
  changeTabsMeta({ name, meta })
}
const handleActiveMenu = (activeMenu: string) => {
  changeActiveMenu(activeMenu)
}

//通用外键变更
const foreignChange = ($event: any, model: any, field: any) => {
  console.log(2)
  console.log(model, $event)
  if (config_table.value.foreign_field[model].next) {
    //表示有级联，去查对应表的数据
    const table = config_table.value.foreign_field[model].next
    getForeignList(table, $event, field)
    //清空级联下级的值
    //form[config_table.foreign[table].field] = ''
  }
}
//通用根据外键ID获取对应数据
const getForeignList = (table: any, event: any, field: any) => {
  console.log(table, event, field)
  let search: any = {}
  search[field] = parseInt(event) > 0 ? parseInt(event) : 0
  search = JSON.stringify(search)
  api_getall(table, {
    search: search,
  }).then((res) => {
    //获取出来的结果赋值给对应级联表中
    const flist = config_table.value.foreign_list
    flist[`${table}_T_${config_table.value.foreign[table].field}`] = res.datalist
  })
}
//通用进入回收站
const recycle = async () => {
  listLoading.value = true
  api_recycle(tablename.value, queryForm).then((res: any) => {
    if (res) {
      is_recycle.value = true
      config_table.value = res.config_table
      list.value = res.datalist
      total.value = res.num
      listLoading.value = false
    }
  })
}
//通用查询
const selectData = (data: any) => {
  Object.assign(queryForm, data)
  getData()
}
//通用普通删除(用于选择删除)
const del = (row: any) => {
  ObjTableRef.value.del(row)
}
//通用彻底删除
const com_del = (row: any) => {
  ObjTableRef.value.com_del(row)
}
//通用恢复操作
const recovery = (row: any) => {
  ObjTableRef.value.recovery(row)
}
//通用添加
const add = () => {
  editRef.value.showEdit(config_table.value)
}
//通用编辑
const edit = (row = {}) => {
  editRef.value.showEdit(row)
}
//通用每页数量修改
const pageChange = (value: number) => {
  queryForm.page = 1
  queryForm.page_num = value
  getData()
}
//通用翻页
const currentChange = (value: number) => {
  queryForm.page = value
  getData()
}

//通用加载前
onMounted(() => {
  getData()
})

onBeforeMount(() => {
  let i = true
  //如果参数是add大于0时，自动弹出添加
  console.log(`${route.query.t}`)
  let param = ''
  let first = true
  if (`${route.query.t}` != 'undefined') {
    tablename.value = `${route.query.t}`
    param += first ? '?' : '&' + `t=${tablename.value}`
    first = false
  }

  if (`${route.query.edit_span}` != 'undefined') {
    edit_span.value = `${route.query.edit_span}`
    param += first ? '?' : '&' + `edit_span=${edit_span.value}`
    first = false
  }

  if (`${route.query.edit_width}` != 'undefined') {
    edit_width.value = `${route.query.edit_width}`
    param += first ? '?' : '&' + `edit_width=${edit_width.value}`
    first = false
  }

  const acmenu = `${dir}/objOri${param}`
  console.log('acmenu', `${acmenu}`)
  handleActiveMenu(`${acmenu}`)

  //如果参数是add大于0时，自动弹出添加
  if (parseInt(`${route.query.add}`) > 0) {
    setInterval(function () {
      if (i && config_table.value) {
        add()
        i = false
      }
    }, 1000)
  }
  //如果参数是edit大于0时，自动弹出编辑
  if (parseInt(`${route.query.edit}`) > 0) {
    setInterval(function () {
      if (i && config_table.value) {
        api_detail(config_table.value.tablename, { id: parseInt(`${route.query.edit}`) }).then((res: any) => {
          if (res.detail) {
            edit(res)
          }
          i = false
        })
      }
    }, 1000)
  }
})
</script>
